package cn.caplike.demo.rabbitmq.api.dlx;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeoutException;

/**
 * @author LiKe
 * @version 1.0.0
 * @date 2020-02-19 12:18
 */
public class Consumer {

    public static void main(String[] args) throws IOException, TimeoutException {
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("111.229.226.114");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");

        // 通过链接工厂创建连接
        Connection connection = connectionFactory.newConnection();

        // 通过连接创建一个 Channel
        Channel channel = connection.createChannel();

        // 这就是一个普通的交换机和队列
        final String exchangeName = "test_dlx_exchange";
        final String routingKey = "dlx.*";
        final String queueName = "test_dlx_queue";

        channel.exchangeDeclare(exchangeName, "topic", true);
        // ~ 需要在正常的队列上声明这个头信息
        Map<String, Object> argumentMap = new HashMap<>(1);
        argumentMap.put("x-dead-letter-exchange", "dlx.exchange");
        channel.queueDeclare(queueName, false, false, true, argumentMap);
        channel.queueBind(queueName, exchangeName, routingKey);

        // 声明 DLX
        channel.exchangeDeclare("dlx.exchange", "topic", false, true, null);
        channel.queueDeclare("dlx.queue", false, false, true, null);
        channel.queueBind("dlx.queue", "dlx.exchange", "#");

        System.out.println("Waiting for message ...");
        channel.basicConsume(queueName, true, new MyConsumer(channel));
    }
}
